package com.tmpt.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.tmpt.beans.A1TemplateColumn;
import com.tmpt.dao.intf.ITemplateDao;
import com.tmpt.dto.Result;
import com.tmpt.service.IChartService;
import com.tmpt.utils.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.genericdao.search.Search;
import com.tmpt.beans.A1TemplateTable;
import com.tmpt.dao.intf.IA1TemplateTableDao;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class ChartService implements IChartService {

	private Logger log = Logger.getLogger(this.getClass());

	@Resource private IA1TemplateTableDao templateTableDao;
	@Resource private TemplateServiceUtils templateServiceUtils;
	private String dataSource = "dsA";

	
    @Override
    public Result chartMultiJson(String keyRandom) {
    	Result result = new Result();
    	try{
        	Search search = new Search();
        	search.addFilterEqual("keyRandom", keyRandom);
        	A1TemplateTable templateTable = (A1TemplateTable)templateTableDao.searchUnique(search);
        	String chartJson = templateTable.getChartJson();
        	String tableName = templateTable.getTableName();
        	JSONObject joDataSource = new JSONObject();
        	//取chart json,为了DB存储方便，可能在json前加特殊字符了
        	chartJson = chartJson.substring(chartJson.indexOf("{"));
        	joDataSource.put("chart", new JSONObject(chartJson));
        	//
        	JSONArray ja_categories = new JSONArray();
        	JSONArray ja_dataset = new JSONArray();
        	
        	//取列
        	for(A1TemplateColumn templateColumn:templateTable.getA1TemplateColumnList()){
        		int chartType = templateColumn.getChartType();
        		String columnName = templateColumn.getColumnName();
        		//1: as categories
        		if(chartType == 1){
        			JSONObject jo_categorie = genCategorie(tableName, columnName);
        			ja_categories.put(jo_categorie);
        		}
        		//2: as dataset
        		if(chartType == 2){
        			JSONObject jo_data = genData(tableName, columnName);
        			ja_dataset.put(jo_data);
        		}
        	}
        	joDataSource.put("categories", ja_categories);
        	joDataSource.put("dataset", ja_dataset);
        	
        	result.setRemark(joDataSource.toString());
    	}catch (Exception e) {
        	return result.fault(e.getLocalizedMessage());
		}
    	return result.success();
    }
	
    /**
       "categories": [{
            "category": [{
                "label": "Mon"
            }, {
                "label": "Tue"
            }, {
                "label": "Wed"
            }, {
                "label": "Thu"
            }, {
                "label": "Fri"
            }, {
                "label": "Sat"
            }, {
                "label": "Sun"
            }]
        }],
     * @param tableName
     * @param columnName
     * @return
     */
    private JSONObject genCategorie(String tableName, String columnName){
		ITemplateDao templateDao = templateServiceUtils.getTemplateDao(this.dataSource);
		List<String> list = templateDao.queryDB(tableName, columnName);
		JSONObject jo_category = new JSONObject();
    	JSONArray ja_category = new JSONArray();
    	for(String value:list){
    		JSONObject jo_category_son = new JSONObject();
    		jo_category_son.put("label", value);
    		ja_category.put(jo_category_son);
    	}
    	jo_category.put("category", ja_category);
    	return jo_category;
    }

    /**
     * {
            "seriesname": "Last Week",
            "data": [{
                "value": "13000"
            }, {
                "value": "14500"
            }, {
                "value": "13500"
            }, {
                "value": "15000"
            }, {
                "value": "15500"
            }, {
                "value": "17650"
            }, {
                "value": "19500"
            }]
        },
     * @param tableName
     * @param columnName
     * @return
     */
    private JSONObject genData(String tableName, String columnName){
		ITemplateDao templateDao = templateServiceUtils.getTemplateDao(this.dataSource);
		List<String> list = templateDao.queryDB(tableName, columnName);
		JSONObject jo_data = new JSONObject();
		jo_data.put("seriesname", columnName);
    	
    	JSONArray ja_data = new JSONArray();
    	for(String value:list){
    		JSONObject ja_data_son = new JSONObject();
    		ja_data_son.put("value", value);
    		ja_data.put(ja_data_son);
    	}
    	jo_data.put("data", ja_data);
    	return jo_data;
    }
	
    

    /**
     * 柱形图
     * @param keyRandom：找模板表，和配置信息
     * @param columnNameData：指定柱表数据列
     * @return
     */
    @Override
    public Result chartSingleJson(String keyRandom, String columnNameData) {
    	Result result = new Result();
    	try{
        	Search search = new Search();
        	search.addFilterEqual("keyRandom", keyRandom);
        	A1TemplateTable templateTable = (A1TemplateTable)templateTableDao.searchUnique(search);
        	String chartJson = templateTable.getChartJson();
        	String tableName = templateTable.getTableName();
        	JSONObject joDataSource = new JSONObject();
        	//取chart json,为了DB存储方便，可能在json前加特殊字符了
        	chartJson = chartJson.substring(chartJson.indexOf("{"));
        	joDataSource.put("chart", new JSONObject(chartJson));
        	
        	//取列
        	for(A1TemplateColumn templateColumn:templateTable.getA1TemplateColumnList()){
        		int chartType = templateColumn.getChartType();
        		String columnName = templateColumn.getColumnName();
        		//1: as categories
        		if(chartType == 1){
        			JSONArray ja_data = genData4ChartColumn(tableName, columnName, columnNameData);
        			joDataSource.put("data", ja_data);
        		}
        	}
        	
        	result.setRemark(joDataSource.toString());
    	}catch (Exception e) {
        	return result.fault(e.getLocalizedMessage());
		}
    	return result.success();
    }
    

    /**
     * "data": [
            {
               "label": "Jan",
               "value": "420000"
            },
            {
               "label": "Feb",
               "value": "810000"
            }]
     * @param tableName
     * @param columnLabel: as chart's label; ps:data
     * @param columnValue: as chart's value; ps:companyA,companyB...
     * @return
     */
    private JSONArray genData4ChartColumn(String tableName, String columnLabel, String columnValue){
		ITemplateDao templateDao = templateServiceUtils.getTemplateDao(this.dataSource);
    	List<Map<String,Object>> list = templateDao.queryDB(tableName, columnLabel, columnValue);
    	JSONArray ja_data = new JSONArray();
    	for(Map<String,Object> map:list){
    		String label = String.valueOf(map.get("label"));
    		String value = String.valueOf(map.get("value"));
    		JSONObject ja_data_son = new JSONObject();
    		ja_data_son.put("label", label);
    		ja_data_son.put("value", value);
    		ja_data.put(ja_data_son);
    	}
    	return ja_data;
    }
    
    
    /**
     * Pie chart
     */
    @Override
    public Result chartPieJson(String keyRandom, int targetTableId) {
    	Result result = new Result();
    	try{
        	Search search = new Search();
        	search.addFilterEqual("keyRandom", keyRandom);
        	A1TemplateTable templateTable = (A1TemplateTable)templateTableDao.searchUnique(search);
        	String chartJson = templateTable.getChartJson();
        	String targetTableName = templateTable.getTableName();
        	String targetPrimaryKey = templateTable.getPrimaryKey();
        	JSONObject joDataSource = new JSONObject();
        	//取chart json,为了DB存储方便，可能在json前加特殊字符了
        	chartJson = chartJson.substring(chartJson.indexOf("{"));
        	JSONObject chartJo = new JSONObject(chartJson);
        	joDataSource.put("chart", chartJo);
        	
        	//取列
        	StringBuilder sb = new StringBuilder();
        	for(A1TemplateColumn templateColumn:templateTable.getA1TemplateColumnList()){
        		int chartType = templateColumn.getChartType();
        		String columnName = templateColumn.getColumnName();
        		//1: as categories
        		if(chartType == 1){
        			//JSONArray ja_data = genData4ChartColumn(tableName, columnName, columnNameData);
        			//joDataSource.put("data", ja_data);
        		}
        		if(chartType == 2){
        			sb.append(columnName).append(",");
        			//JSONArray ja_data = genData4ChartColumn(tableName, columnName, columnNameData);
        			//joDataSource.put("data", ja_data);
        		}
        	}
        	if(sb.length()>0)sb.deleteCharAt(sb.length()-1);
        	String targetColumns = sb.toString();
        	//.out.println("======targetColumns:"+targetColumns);
        	JSONArray ja_data = genData4ChartPie(targetTableName, targetColumns, targetPrimaryKey, targetTableId);
        	joDataSource.put("data", ja_data);
        	//
        	
        	
        	result.setRemark(joDataSource.toString());
    	}catch (Exception e) {
    		e.printStackTrace();
        	return result.fault(e.getLocalizedMessage());
		}
    	return result.success();
    }
    

    private JSONArray genData4ChartPie(String targetTableName, String targetColumns, String targetPrimaryKey, int targetTableId){
		ITemplateDao templateDao = templateServiceUtils.getTemplateDao(this.dataSource);
    	targetPrimaryKey = StringUtils.isNull(targetPrimaryKey)?"id":targetPrimaryKey;
    	List<Map<String,Object>> list = null;
    	if(targetTableId == 0){
    		//查最后一条记录
    		list = templateDao.queryDBLast(targetTableName, targetColumns, targetPrimaryKey);
    	}else{
    		list = templateDao.queryDB(targetTableName, targetColumns, targetPrimaryKey,targetTableId);
    	}
    	if(list == null || list.size()==0){
    		return null;
    	}

    	JSONArray ja_data = new JSONArray();
    	Map<String,Object> map = list.get(0);
    	Iterator it = map.keySet().iterator();
    	while(it.hasNext()){
    		String label = String.valueOf(it.next());
    		String value = String.valueOf(map.get(label));
    		JSONObject ja_data_son = new JSONObject();
    		ja_data_son.put("label", label);
    		ja_data_son.put("value", value);
    		ja_data.put(ja_data_son);
    	}
    	
    	return ja_data;
    }

    @Override
    public Result testAddCheck(List<Map<String,Object>> paramList){
    	Result result = new Result();
    	//.out.println("-----------testAddCheck------");

    	//result.setRemark("return");
    	result.setRemark("continue");
    	return result.success();
    }

    @Override
    public Result testEditCheck(List<Map<String,Object>> paramList){
    	Result result = new Result();
    	//.out.println("-----------testEditCheck------");
    	//[{columnName=dataCompanyA, columnValue=12000}, {columnName=dataCompanyB, columnValue=32001}, {columnName=date, columnValue=2016-11-07}, {columnName=deleteFlag, columnValue=0}, {columnName=dataCompanyC, columnValue=33}, {columnName=modifyMan, columnValue=admin123}, {columnName=modifyDate, columnValue=2016-11-08 14:08:44.426}]
    	//.out.println(paramList);
    	for(Map<String,Object> map : paramList){
    		String columnName = map.get("columnName").toString();
    		String columnValue = map.get("columnValue").toString();
    		if(columnName.equals("dataCompanyB")){
    			if(StringUtils.isNull(columnValue)){
    		    	return result.fault("dataCompanyB is NULL");
    			}
    		}
    	}
    	
    	//result.setRemark("return");
    	result.setRemark("continue");
    	//return result.fault("test for fault");
    	return result.success();
    }
    
}
